<?php

class TXT_Controller extends CI_Controller {

    function __construct() {

        parent::__construct();

        // 加载session
        $this->load->library('session');

        // 加载URL操作
        $this->load->helper('url');

    }

    /**
     * _remap 
     * 重写路由的方法，添加before方法
     * 
     * @param string $method 方法名
     * @param array $params 参数
     * @access protected
     * @return misc
     */
    function _remap($method, $params = array()) {

        // before action
        $this->_before($method);

        // call method
        if (method_exists($this, $method)) {
            return call_user_func_array(array($this, $method), $params);
        }

        show_404();
    }

    /**
     * _before 
     * 
     * @access protected
     * @return void
     */
    protected function _before($method) {

        // load config
        $this->config->load('txt');

        return;
    }

    protected function _isLogin() {

        $isLogin = $this->session->userdata('l');

        return $isLogin === true;
    }

    protected function _checkLogin() {

        if (!$this->_isLogin()) {
            redirect('/login');
        }
    }

    protected function _ajaxMessage($code, $message = null, $result = array()) {

        if ($message === null) {
            if ($code > 0) {
                $message = '操作失败';
            } else {
                $message = '操作成功';
            }
        }

        $code = intval($code);
        if (!$code) {
            $code = 0;
        }

        $result = array('code' => $code,
                        'message' => $message,
                        'result' => $result
                        );

        return $this->output->set_output(json_encode($result));
    }

    /**
     * _initializeUserData 
     * 初始化用户数据
     * 
     * @param integer $uid 用户ID
     * @access protected
     * @return array
     */
    protected function _initializeUserData($uid = 0) {

        if (!$uid) {
            $uid = intval($this->session->userdata('uid'));
        }

        $this->load->model('account_model');
        $userInfo = $this->account_model->getAccountByUid($uid);

        return $userInfo;
    }

    protected function _render($tpl, $data) {

        $data['user'] = $this->_initializeUserData();

        return $this->load->view($tpl, $data);
    }
}
